import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

const useUserStore = defineStore('userStore', () => {
  // 定义响应式 userInfo
  const userInfo = ref<{ id: string; username: string; nickname: string }>({
    id: '',
    username: '',
    nickname: ''
  })

  const loadUserInfo = () => {
    const user = window.localStorage.getItem('user')
    if (user) {
      userInfo.value = JSON.parse(user)
    }
  }

  loadUserInfo()

  // **手动获取用户信息**
  const getUserInfo = () => {
    return userInfo.value
  }

  // 设置用户信息
  const setUserInfo = (val: { id: string; username: string; nickname: string }) => {
    userInfo.value = val
    window.localStorage.setItem('user', JSON.stringify(val))
  }

  return {
    userInfo,
    getUserInfo,
    setUserInfo
  }
})

export default useUserStore
